package sort

import (
	"reflect"
)

type Comparator func(i, j int) bool

func Slice(arr interface{}, less Comparator) {
	value := reflect.ValueOf(arr)
	quickSort(value, 0, value.Len()-1, less)
}

func quickSort(arr reflect.Value, start, end int, less Comparator) {
	if start < end {
		var i = start
		for j := start; j < end; j++ {
			if less(j, end) {
				swap(arr.Index(j), arr.Index(i))
				i++
			}
		}
		swap(arr.Index(i), arr.Index(end))
		quickSort(arr, start, i-1, less)
		quickSort(arr, i+1, end, less)
	}
}

func swap(a, b reflect.Value) {
	tmp := a.Interface()
	a.Set(reflect.ValueOf(b.Interface()))
	b.Set(reflect.ValueOf(tmp))
}
